import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Row, Col, Select, message, notification } from 'antd';
import { mobile as mobileRule } from '@/utils/rule';
import { getCode } from '@/services/user';
import { getCaptchaImage, getSaftCaptchaOp, bindingMobileOp } from '../service';
import { MailTwoTone } from '@ant-design/icons';
import styles from './index.module.less';

const { Option } = Select;

export default ({ type, unionid, handleBindBack }) => {

	const [count, setCount] = useState(0);
	const [captchaObj, setObj] = useState({});

	const { image: imgCaptcha, key } = captchaObj;

	const [form] = Form.useForm();

	const onFinish = values => {
		if(type == 'bind'){
      bindingMobileOp({
				unionid,
				url: `http://${window.location.host}`,
				industrialBeltFlag: INDUSTRIAL_BELT_FLAG,
				mobile:  values.mobile,
				code: values.sms_code,
			}).then(()=>{
				handleBindBack({unionid, mobile:values.mobile});
			})
		}else{
			handleBindBack({mobile:values.mobile, sms_code:values.sms_code});
		}
	};

	const prefixSelector = (
		<Form.Item name="prefix" noStyle>
			<Select style={{ width: 80 }} size='large'>
				<Option value="86">+86</Option>
				<Option value="87">+87</Option>
			</Select>
		</Form.Item>
	);

	useEffect(()=>{
		if(count){
		 setTimeout(()=>{
			 setCount(count-1);
		 }, 1000)
		}
	 },[count])

	 useEffect(()=>{
		if(imgCaptcha){
		 form.validateFields(['Captcha-Code'])
		}
	 },[imgCaptcha])

	const handleGetCode = async (val) => {
		const { success, data } = await getCode({
			mobile: val,
			type: type == 'bind' ? '15' : '2',
			industrialBeltFlag: INDUSTRIAL_BELT_FLAG,
			appType: '2'
		})
		
		if (success) {
		  if(data){
        message.success('验证码发送成功！');
        setCount(59);
      }else{
        getImgCaptchaFunc(true);
      }
		}
	}

	const getImgCaptchaFunc = async (bool) => {
		const res = await getCaptchaImage();
    if(res?.key && bool){
      notification.info({
        message: `温馨提示`,
        description: '鉴于安全因素，请输入图形验证码，验证通过后方可重新获取手机验证码',
      });   
      setObj(res);
    }
 }

 //获取手机验证码
 const onGetCaptcha = async () => {
	if(imgCaptcha){
		form.validateFields([ 'Captcha-Code', 'mobile' ]).then(val=>{
			getSaftCaptchaFunc(val);
		})
	}else{
		form.validateFields([ 'mobile' ])
		.then(values => {
			handleGetCode(values.mobile);
		})
	}
}

const getSaftCaptchaFunc = async (val) => {
	const { success } = await getSaftCaptchaOp({
		...val,
		type: '2',
		appType: '2',
		industrialBeltFlag: INDUSTRIAL_BELT_FLAG,
		'Captcha-Key': key, 
	});
	if(success){
	  message.success('验证码发送成功！');
    setCount(59);
		setObj({});
	}else{
		getImgCaptchaFunc();
		form.setFieldsValue({
			'Captcha-Code': null,
			'smsCode': null
		})
	}
}

	return (
		<Form
			initialValues={{ 
				prefix: '86',
			}}
			onFinish={onFinish}
			style={{ width: '100%' }}
			form={form}
			name='mobile-login'
		>
			<Form.Item
				name="mobile"
				rules={[
					{ required: true, message: '请输入手机号' },
					mobileRule
				]}
			>
				<Input size='large' addonBefore={prefixSelector} placeholder="请输入手机号" />
			</Form.Item>
			{
				imgCaptcha && <Row gutter={8}>
				<Col span={16}>
					<Form.Item
						name="Captcha-Code"
						rules={[
							{ required: true, message: '请输入验证码' },
							{ pattern: /^[A-Za-z0-9]+$/, message: '输入格式有误' },
						]}
					>
						<Input size="large" prefix={<MailTwoTone className={styles.prefixIcon} />} placeholder="请输入验证码！" />
					</Form.Item>
				</Col>
				<Col span={8}>
				   <img alt="captcha" src={imgCaptcha} className={styles.getImgCaptcha} onClick={getImgCaptchaFunc} />
				</Col>
			</Row>
			}
			<Row gutter={8}>
				<Col span={16}>
					<Form.Item
						name="sms_code"
						rules={[{ required: true, message: '请输入验证码' }]}
					>
						<Input size="large" prefix={<MailTwoTone className={styles.prefixIcon} />} placeholder="请输入验证码！" autoComplete='off' />
					</Form.Item>
				</Col>
				<Col span={8} style={{ textAlign: 'right' }}>
					<Button disabled={count} style={{ width: '100%', fontSize: '14px', padding: 0 }} onClick={onGetCaptcha} size='large'>{count ? `${count}s` : '获取验证码'}</Button>
				</Col>
			</Row>
			{
				type != 'bind' && (<div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '16px' }}>
				<a className="login-form-forgot" href="#/user/register">
					没有账号？去注册
				</a>
			</div>)
			}
			<Form.Item >
				<Button size="large" style={{ width: '100%' }} type="primary" htmlType="submit" className="login-form-button">
					{ type == 'bind' ? '绑定' : '登录' }
				</Button>
			</Form.Item>
		</Form>
	)
}

